import { useEffect, useState } from 'react'
import ArticleItem from '../ArticleItem'
import styles from './index.module.scss'
import { useDispatch, useSelector } from 'react-redux'
import {
  getArticleListAsync,
  getMoreArticleListAsync,
} from '@/store/actions/home'
import { PullToRefresh, InfiniteScroll } from 'antd-mobile'
/**
 * 文章列表组件
 * @param {String} props.channel_id 当前文章列表所对应的频道ID
 */
const ArticleList = ({ active_id, channel_id }) => {
  const dispatch = useDispatch()
  // 获取文章列表数据
  const res = useSelector((state) => state.home.articles[channel_id])
  useEffect(() => {
    // 如果redux中有该数据了，没必要再调接口存储一次
    if (res) return
    if (channel_id === active_id) {
      dispatch(getArticleListAsync(channel_id, Date.now()))
    }
  }, [dispatch, channel_id, active_id, res])

  // 下拉刷新
  const onRefresh = () => {
    // 下拉刷新获取的是最新的数据，替换原来的数据
    dispatch(getArticleListAsync(channel_id, Date.now()))
  }

  // 上拉加载
  const [hasMore, setHasMore] = useState(true) // 值为true时才能发起请求
  const [loading, setLoading] = useState(true) // 节流阀，避免上一次请求未完成这次请求又来了
  const loadMore = async () => {
    if (!hasMore) return
    // 没有更多数据的处理
    if (!timestamp) {
      // 代表没有更多的数据了，不需要发起请求
      setHasMore(false)
      return
    }
    // 只允许当前激活的频道才发请求
    if (channel_id !== active_id) return

    // 发送网络请求：channel_id、timestamp
    if (loading) {
      setLoading(false)
      await dispatch(getMoreArticleListAsync(channel_id, timestamp))
      setLoading(true)
    }
  }

  // 如果没有redux数据，直接返回null
  if (!res) return null
  const { list, timestamp } = res
  return (
    <div className={styles.root}>
      <PullToRefresh onRefresh={onRefresh}>
        <div className="articles">
          {list.map((item) => (
            <div key={item.art_id} className="article-item">
              <ArticleItem channel_id={channel_id} article={item}></ArticleItem>
            </div>
          ))}
        </div>
      </PullToRefresh>
      <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
    </div>
  )
}

export default ArticleList
